<template>
    <div class="login">
        <div>
            <loading loader="spinner" :active.sync="logging"></loading>
            <div>
                <img
                    alt="Vue logo"
                    src="../assets/image/ytologo.png"
                    width="100%"
                />
            </div>
            <mu-text-field
                v-model="UserName"
                label="UserName"
                label-float
                help-text="请输入用户名"
                icon="account_circle"
            ></mu-text-field>
            <br />
            <mu-text-field
                v-model="Password"
                label="Password"
                label-float
                icon="locked"
                help-text="请输入密码"
                :action-icon="visibility ? 'visibility_off' : 'visibility'"
                :action-click="() => (visibility = !visibility)"
                :type="visibility ? 'text' : 'password'"
            ></mu-text-field>
            <br />
            <mu-row gutter>
                <mu-col span="3" offset="3">
                    <mu-flex justify-content="center">
                        <mu-button
                            :ripple="false"
                            full-width
                            style="margin-top: 20px"
                            @click="changeCode"
                            flat
                        >
                            <img alt="点击重新加载" :src="codeSrc" />
                        </mu-button>
                    </mu-flex>
                </mu-col>
                <mu-col span="3">
                    <mu-text-field
                        full-width
                        v-model="code"
                        label="VerifyCode"
                        label-float
                        help-text="请输入验证码"
                    ></mu-text-field>
                </mu-col>
            </mu-row>
            <br />
            <mu-checkbox
                label="记住账号密码"
                v-model="IsRemember"
                bind:change="remember"
            ></mu-checkbox>
            <br />
            <br />

            <mu-button
                color="primary"
                style="margin-bottom: 55px"
                :disabled="logging"
                @click="OnLine"
                >登录</mu-button
            >
        </div>
        <div style="position: fixed; bottom: 15px; left: 0; width: 100%">
            <mu-button flat :ripple="false">
                <mu-icon left value="info"></mu-icon>
                {{ Version }}
            </mu-button>
        </div>
    </div>
</template>

<script>
// let cityCodeJson = require('../assets/json/cityCode');
// let linq = require('linq');
import VueLoading from 'vue-loading-overlay';
import 'vue-loading-overlay/dist/vue-loading.css';
export default {
    name: 'Login',
    data () {
        return {
            codeKey: '',
            code: '',
            codeSrc: '',
            Password: '',
            UserName: '',
            IsRemember: false,
            visibility: false,
            Version: 'Version',
            logging: false,
            timer: null,
        };
    },
    components: {
        loading: VueLoading,
    },
    methods: {
        changeCode () {
            let _this = this;
            this.$axios({
                method: 'POST',
                url: 'Login/LoginCode',
            })
                .then(function (res) {
                    console.info(res);
                    if (res.data.msg == '操作成功！') {
                        _this.codeSrc =
                            'data:image/jpeg;base64,' + res.data.data.jpg;
                        _this.codeKey = res.data.data.codeKey;
                    } else {
                        //
                    }
                })
                .catch(function (err) {
                    console.info(err);
                });
        },
        onSuccess () {
            // let _this = this;
        },
        onFail () {
            // let _this = this;
        },
        getgaode () {
            // let _this = this;
        },
        OnLine () {
            let _this = this;
            _this.logging = true;
            _this
                .$axios({
                    url: 'Login/IsOnLine',
                    method: 'get',
                    async: false,
                })
                .then(function (res) {
                    console.info(res);
                    // TODO 正式版注释掉这行
                    _this.login();

                    _this
                        .$axios({
                            method: 'post',
                            url: 'Test/GetTime',
                        })
                        .then(function (res) {
                            let time2 = new Date();
                            console.info(res.data.msg);
                            window.localStorage['datetime'] = res.data.msg;
                            let date2 = res.data.msg.replace(/-/g, '/');
                            let time1 = new Date(date2);
                            if (
                                time2 - time1 > 1000 * 60 * 5 ||
                                time2 - time1 < -1 * 1000 * 60 * 5
                            ) {
                                alert('当前手机时间不正确！前先校准时间！');
                                _this.logging = false;
                                return;
                            }

                            // let mam = api.require('mam');
                            // mam.checkUpdate(function (ret, err) {
                            //     console.info(ret);
                            //     if (ret) {
                            //         let result = ret.result;
                            //         if (
                            //             result.update == true &&
                            //             result.closed == false
                            //         ) {
                            //             let str =
                            //                 '发现新版本:' +
                            //                 result.version +
                            //                 '，请重启APP进行更新';
                            //             _this.$toast(str);
                            //             _this.logging = false;
                            //             return;
                            //         } else {
                            //             _this.login();
                            //         }
                            //     } else {
                            //         _this.login();
                            //     }
                            // });
                        })
                        .catch(function (err) {
                            console.info(err);
                            _this.$toast('请检查网络！');
                            _this.logging = false;
                            return;
                        });
                })
                .catch(function (err) {
                    console.info(err);
                    _this.$toast('请检查网络！');
                    _this.logging = false;
                    return;
                });
        },
        login: function () {
            let _this = this;
            if (_this.UserName == '' || _this.Password == '') {
                _this.$toast('用户名或密码不能为空！');
                _this.logging = false;
                return;
            }

            var storage = window.localStorage;
            if (_this.IsRemember == true) {
                storage['UserName'] = _this.UserName;
                storage['Password'] = _this.Password;
                storage['IsRemember'] = _this.IsRemember;
            } else {
                storage['UserName'] = '';
                storage['Password'] = '';
                storage['IsRemember'] = _this.IsRemember;
            }

            let data = new FormData();
            data.append('username', _this.UserName);
            data.append('userpwd', _this.Password);
            data.append('codeKey', _this.codeKey);
            data.append('code', _this.code);
            _this
                .$axios({
                    method: 'POST',
                    url: 'Login/Login',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    data: data,
                })
                .then(function (res) {
                    console.info(res);
                    _this.$toast(res.data.msg);
                    // let ctjson = linq.from(cityCodeJson).toArray();
                    // _this.global.cityCode = ctjson;
                    // linq.from(res.data.data.city).forEach((e) => {
                    //     _this.global.cityCode.push(e);
                    // });
                    // console.log(_this.global.cityCode);
                    if (res.data.msg == '操作成功！') {
                        clearTimeout(_this.timer);
                        _this.$parent.teamname = res.data.data.chinaName;
                        _this.$parent.chinaName = res.data.data.teamName;
                        _this.global.currentCityCode = res.data.data.teamId;
                        if (_this.global.UserIdlist.length == 2) {
                            _this.global.UserIdlist.splice(0, 1);
                        }
                        if (
                            window.localStorage['loginid'] ==
                            res.data.data.teamId
                        ) {
                            window.localStorage['loginuser'] = '同一用户';
                        } else {
                            if (window.localStorage['loginid'] != undefined) {
                                window.localStorage['loginuser'] = '不同用户';
                                //console.log("不同");
                                _this.global.ClearStore('whole');
                                console.log('清除数据');
                            }
                        }
                        window.localStorage['loginid'] = res.data.data.teamId;
                        _this.global.UserIdlist.push(res.data.data.teamId);
                        _this.global.Refreshlist = [1, 1, 1, 1, 1];
                        _this.logging = false;
                        _this.$router.push('Menus');
                        history.pushState(null, null, document.URL);
                    } else {
                        _this.logging = false;
                    }
                })
                .catch(function (err) {
                    console.info(err);
                    _this.logging = false;
                });
        },
        remember: function () {
            let storage = window.localStorage;
            this.UserName = storage['UserName'];
            this.Password = storage['Password'];
            if (storage['IsRemember'] == 'true') {
                this.IsRemember = true;
            } else {
                this.IsRemember = false;
            }
        },
        gettime () {
            this.$axios({
                method: 'post',
                url: 'Test/GetTime',
            })
                .then(function (res) {
                    return res.data.msg;
                })
                .catch(function (err) {
                    console.info(err);
                    return null;
                });
        },
    },
    watch: {
        codeKey () {
            clearTimeout(this.timer);
            console.info('Watching CodeKey ......');
            this.timer = setTimeout(() => {
                this.changeCode();
            }, 55000);
        },
    },
    activated: function () {
        let _this = this;
        _this.remember();
        _this.global.loginpath = _this.$route.path;
        _this.$parent.title = 'PDA登录';
        _this.changeCode();
        _this.logging = false;
    },
    created: function () {
        let _this = this;
        _this.logging = false;
        let time = _this.global.getTime(true);
        console.info(time);
        _this.remember();
        _this.global.loginpath = _this.$route.path;
        _this.$parent.title = 'PDA登录';
        _this.$parent.teamname = '请登录!';
        _this.$parent.chinaName = '供应商';
        _this.changeCode();


        window.apiready = function () {
          api.alert({
              title: 'testtitle',
              msg: 'testmsg',
          });
        }

    },
    updated () {
        // let _this = this;
    },
    destroyed () {
        let _this = this;
        clearTimeout(_this.timer);
    },
};
</script>

<style scoped>
</style>
